<template>
	<view class="search-page">
		<!-- 顶部搜索栏 -->
		<view class="search-header">
			<view class="back-btn" @click="goBack">
				<text class="back-icon">←</text>
			</view>
			<view class="search-input-box">
				<text class="search-icon">🔍</text>
				<input 
					type="text" 
					class="search-input" 
					v-model="searchKeyword"
					placeholder="搜索目的地 / 景点 / 酒店"
					confirm-type="search"
					@confirm="handleSearch"
					focus
				/>
			</view>
			<view class="search-btn" @click="handleSearch">
				搜索
			</view>
		</view>
		
		<!-- 搜索内容区 -->
		<view class="search-content">
			<!-- 历史搜索 -->
			<view class="history-section" v-if="historyList.length > 0">
				<view class="section-header">
					<text class="section-title">历史搜索</text>
					<view class="clear-btn" @click="clearHistory">
						<text class="clear-icon">🗑️</text>
					</view>
				</view>
				<view class="tag-list">
					<view 
						v-for="(item, index) in historyList" 
						:key="index" 
						class="tag-item"
						@click="selectKeyword(item)"
					>
						{{ item }}
					</view>
				</view>
			</view>
			
			<!-- 热门推荐 -->
			<view class="hot-section">
				<view class="section-header">
					<text class="section-title">热门推荐</text>
				</view>
				<view class="tag-list">
					<view 
						v-for="(item, index) in hotList" 
						:key="index" 
						class="tag-item hot-tag"
						@click="selectKeyword(item)"
					>
						{{ item }}
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			searchKeyword: '',
			historyList: [],
			hotList: [],
			userId: null
		};
	},
	
	onLoad(options) {
		console.log('搜索页面加载...');
		
		// 获取用户ID
		const userInfo = uni.getStorageSync('userInfo');
		if (userInfo && userInfo.id) {
			this.userId = userInfo.id;
			console.log('用户ID:', this.userId);
		} else {
			// 如果没有登录，使用默认用户ID
			this.userId = 1;
			console.log('使用默认用户ID: 1');
		}
		
		// 如果传入了关键词，直接搜索
		if (options.keyword) {
			this.searchKeyword = options.keyword;
		}
		
		// 加载搜索建议
		this.loadSearchSuggest();
	},
	
	methods: {
		// 加载搜索建议（历史+热门）
		async loadSearchSuggest() {
			console.log('开始加载搜索建议...');
			console.log('baseUrl:', this.$baseUrl);
			console.log('userId:', this.userId);
			
			try {
				const res = await this.$http({
					url: '/api/search/suggest',
					method: 'GET',
					data: {
						userId: this.userId
					}
				});
				
				console.log('API响应:', res);
				
				if (res.data && res.data.code === 200) {
					this.historyList = res.data.data.history || [];
					this.hotList = res.data.data.hot || [];
					console.log('历史搜索:', this.historyList.length, '条');
					console.log('热门推荐:', this.hotList.length, '条');
					
					if (this.hotList.length === 0) {
						// 如果热门推荐为空，加载默认数据
						console.log('热门推荐为空，加载默认数据');
						this.loadDefaultHotSearch();
					}
				} else {
					console.error('API返回错误:', res.data);
					// 加载默认热门搜索
					this.loadDefaultHotSearch();
				}
			} catch (e) {
				console.error('加载搜索建议失败：', e);
				// 加载默认热门搜索
				this.loadDefaultHotSearch();
			}
		},
		
		// 加载默认热门搜索（当API失败时）
		loadDefaultHotSearch() {
			console.log('加载默认热门搜索...');
			this.hotList = [
				'狼牙山', '故宫博物馆', '北京万达文华酒店', 
				'泸山温泉', '周边游', '世界杯',
				'热门推荐', '热门推荐三', '热门推荐五', '记录四'
			];
		},
		
		// 执行搜索
		async handleSearch() {
			const keyword = this.searchKeyword.trim();
			console.log('执行搜索:', keyword);
			
			if (!keyword) {
				uni.showToast({
					title: '请输入搜索关键词',
					icon: 'none'
				});
				return;
			}
			
			// 保存搜索历史
			if (this.userId) {
				try {
					await this.$http({
						url: '/api/search/history',
						method: 'POST',
						data: {
							userId: this.userId,
							keyword: keyword,
							searchType: 1
						}
					});
					console.log('搜索历史已保存');
				} catch (e) {
					console.error('保存搜索历史失败：', e);
				}
			}
			
			// 跳转到搜索结果页
			console.log('跳转到搜索结果页...');
			uni.navigateTo({
				url: `/pages/search/result?keyword=${encodeURIComponent(keyword)}`
			});
		},
		
		// 选择关键词
		selectKeyword(keyword) {
			this.searchKeyword = keyword;
			this.handleSearch();
		},
		
		// 清空历史
		clearHistory() {
			uni.showModal({
				title: '提示',
				content: '确定要清空搜索历史吗？',
				success: async (res) => {
					if (res.confirm && this.userId) {
						try {
							await this.$http({
								url: `/api/search/history?userId=${this.userId}`,
								method: 'DELETE'
							});
							
							this.historyList = [];
							uni.showToast({
								title: '已清空',
								icon: 'success'
							});
						} catch (e) {
							console.error('清空历史失败：', e);
							uni.showToast({
								title: '清空失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 返回
		goBack() {
			uni.navigateBack();
		}
	}
};
</script>

<style scoped>
.search-page {
	min-height: 100vh;
	background-color: #F5F5F5;
}

/* 顶部搜索栏 */
.search-header {
	display: flex;
	align-items: center;
	padding: 20rpx;
	background-color: #FFFFFF;
	border-bottom: 1px solid #EEEEEE;
}

.back-btn {
	padding: 10rpx;
	margin-right: 10rpx;
	cursor: pointer;
}

.back-icon {
	font-size: 40rpx;
	color: #333333;
}

.search-input-box {
	flex: 1;
	display: flex;
	align-items: center;
	background-color: #F5F5F5;
	border-radius: 50rpx;
	padding: 16rpx 24rpx;
	margin-right: 10rpx;
}

.search-icon {
	font-size: 32rpx;
}

.search-input {
	flex: 1;
	margin-left: 12rpx;
	font-size: 28rpx;
	color: #333333;
}

.search-btn {
	padding: 12rpx 24rpx;
	background-color: #1890FF;
	color: #FFFFFF;
	border-radius: 50rpx;
	font-size: 28rpx;
}

/* 内容区 */
.search-content {
	padding: 30rpx;
}

/* 区块标题 */
.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 24rpx;
}

.section-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333333;
}

.clear-btn {
	padding: 8rpx;
	cursor: pointer;
}

.clear-icon {
	font-size: 32rpx;
}

/* 标签列表 */
.tag-list {
	display: flex;
	flex-wrap: wrap;
	gap: 20rpx;
}

.tag-item {
	padding: 16rpx 32rpx;
	background-color: #F5F5F5;
	border-radius: 50rpx;
	font-size: 28rpx;
	color: #666666;
}

.hot-tag {
	background-color: #E6F7FF;
	color: #1890FF;
}

/* 区块间距 */
.history-section {
	margin-bottom: 50rpx;
}

.hot-section {
	margin-bottom: 30rpx;
}
</style>
